<?php
/**
 * 汽车模型类
 * @author zengnz
 *
 */

class CarModel extends CommonModel
{
	//设置car_info 表个数
	private static $_carInfoTables = 5;
	
	private $_Model = '';
	
	public function __construct() {
		$this -> _Model = new Model();		
	}
	
	/**
	 * 根据ID获取汽车相关文章
	 * @param integer $id
	 */
	public function getCarInfoById($id, $cateId) {
		if (!$id || !$cateId)
			return -1;
		
		$key = CacheModel::COMMONCACHE . 'CARINFO:CATE:' . $cateId . ':ID:' . $id;
		$CacheModel = new CacheModel();
		
		//$info = $CacheModel -> cache -> get($key);		
		//if (!$info) {
			$tbSuffix = $cateId % self::$_carInfoTables;	
			$table = 'car_info_'.$tbSuffix;
			$sql = 'id = ' . $id;	
			
			$info = $this -> _Model -> table($table) -> where($sql) -> find();
			
			// 缓存查询信息，保存键名
		//}
		
		return $info;
	}
	
	/**
	 * 保存汽车相关文章
	 * @param array $data
	 * @param integer $cateId
	 */
	public function addCarInfo($data, $cateId) {
		if (!$data || !$cateId)
			return -1;
		
		$tbSuffix = $cateId % self::$_carInfoTables;
		$table = 'car_info_'.$tbSuffix;
		
		$flag = $this -> _Model -> table($table) -> add($data);
		if ($flag)
			// 清除缓存
		
		return $flag;	
	}
	
	/**
	 * 更新汽车相关文章
	 * @param array $data
	 * @param string $where
	 * @param integer $cateId
	 */
	public function updateCarInfo($data,$where,$cateId) {
		if (!$data || !$where || !$cateId)
			return -1;
		
		$tbSuffix = $cateId % self::$_carInfoTables;
		$table = 'car_info_'.$tbSuffix;
		
		$info = $this -> _Model -> table($table)
				-> where($where) 
				-> find();
		
		if (!$info)
			return -2;
		
		$flag = $this -> _Model -> table($table) 
				-> where($where) 
				-> save($data);
		
		if ($flag)
			// 清除缓存
		
		return $flag;
	}
	
	/**
	 * 获取最近的文章信息，每个类型至少一篇文章
	 */
	public function getLatestCarInfoList($cateId, $num=10) {
		$key = 'CATEID:'.$cateId.':NUM:'.$num;
		$tbSuffix = $cateId % self::$_carInfoTables;
		$table = 'car_info_'.$tbSuffix;
		
		$sql = 'select * from `'.$table.'` where id in (select id from `'.$table.'` group by type limit 3)' ;
		
		$info = $this -> _Model -> table($table)
				-> where()
				-> selectAll();
		
	} 
	
	
}